package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import java.util.Date;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    ApUserFanMapper apUserFanMapper;
    @Autowired
    ApUserFollowMapper apUserFollowMapper;
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;

    @Override
    @Transactional
    /**
     * 用户关注，取消关注方法
     */
    public ResponseResult follow(UserRelationDto dto) {
        //参数校验
        if (dto == null || dto.getAuthorId() == null || (Integer.valueOf(dto.getOperation()) != 0 && Integer.valueOf(dto.getOperation()) != 1)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据作者id查询作者信息
        ApAuthor apAuthor = articleFeign.selectById(dto.getAuthorId());
        if (apAuthor == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }
        ApUser loginUser = AppUserThreadLocalUtils.getUser();
        if (loginUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录再关注");
        }
        //判断是关注还是取消关注
        if (Integer.valueOf(dto.getOperation()) == 0) {
            //执行关注方法
            return followByUserId(loginUser.getId(), apAuthor,dto.getArticleId());
        } else {
            //执行取消关注方法
            return followCannelByUserId(loginUser.getId(), apAuthor);
        }
    }

    /**
     * 关注方法
     *
     * @param loginUserId
     * @param apAuthor
     */
    private ResponseResult followByUserId(Integer loginUserId, ApAuthor apAuthor, Long articleId) {
        //封装用户id和作者id条件查询
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, loginUserId)
                .eq(ApUserFollow::getFollowId, apAuthor.getId()));
        if (apUserFollow != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "已经添加过关注了");
        }
        //插入关注关系
         apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(loginUserId);
        apUserFollow.setFollowId(apAuthor.getId());
        apUserFollow.setFollowName(apAuthor.getName());
        apUserFollow.setLevel((short) 0);
        apUserFollow.setIsNotice(false);
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);

        //查询粉丝表
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, loginUserId)
                .eq(ApUserFan::getUserId, apAuthor.getId()));
        if(apUserFan!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "已经存在该粉丝了");
        }
        apUserFan = new ApUserFan();
        ApUser apUser = apUserMapper.selectById(loginUserId);
        apUserFan.setUserId(apAuthor.getId());
        apUserFan.setFansId(Long.valueOf(loginUserId));
        apUserFan.setFansName(apUser.getName());
        apUserFan.setLevel((short)0);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setIsDisplay(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsShieldComment(false);
        apUserFanMapper.insert(apUserFan);

        //创建关注行为对象，通过kafka发送给消费端
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setArticleId(articleId);
        dto.setUserId(loginUserId);
        dto.setFollowId(apAuthor.getId());
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC,JSON.toJSONString(dto));

        return ResponseResult.okResult();

    }

    /**
     * 取消关注方法
     *
     * @param loginUserId
     * @param apAuthor
     */
    private ResponseResult followCannelByUserId(Integer loginUserId, ApAuthor apAuthor) {
        //根据用户id和作者id删除关系
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, loginUserId)
                .eq(ApUserFollow::getFollowId, apAuthor.getId()));

        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, loginUserId)
                .eq(ApUserFan::getUserId, apAuthor.getId()));
        return ResponseResult.okResult();
    }
}
